package com.faxsun.web.controller.user;

import javax.servlet.http.HttpServletRequest;

import mblog.web.controller.BaseController;
import mtons.modules.pojos.UserContextHolder;
import mtons.modules.pojos.UserProfile;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.persist.entity.FollowListPO;
import com.faxsun.core.pojos.enums.FollowStatusType;
import com.faxsun.core.service.FollowListService;
import com.faxsun.core.service.UserService;
import com.faxsun.web.utils.MobileDetect;

@Controller
@RequestMapping("/fl")
@Transactional(rollbackFor = { Exception.class })
public class FollowListController extends BaseController {

	@SuppressWarnings("unused")
	private static final Logger LOG = LoggerFactory.getLogger(FollowListController.class);

	@Autowired
	protected FollowListService followListService;

	@Autowired
	protected UserService userService;
	
	public static int THUMBSUP_ANONYMOUS_CODE = 100;   
    public static int THUMBSUP_ANONYMOUS_ALREADY_CODE = 101;

	@RequestMapping(value = "/follow", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String follow(HttpServletRequest request, ModelMap model) {
		Object flarray = findFLFromRequestParam(request, false);
		FollowListPO fl = null;
		RetJson ret = null;

		if (flarray instanceof RetJson) {
			ret = (RetJson) flarray;
			
			if(ret.code==-2){
				return ret.toString();
			}
			
			fl = new FollowListPO();

			fl.setFollower_id(Long.parseLong(ret.getFollowerId()));
			//被关注的商品tag id或者user id或者资讯post id
			fl.setUid(Long.parseLong(ret.getUid()));
			fl.setItem_type(Integer.parseInt(ret.getItemType()));
			fl.setThumbsup(false);// initial to un-thumbsup
		} else {
			fl = (FollowListPO) flarray;

			long userId = ((FollowListPO) fl).getFollower_id();
			ret = new RetJson(-1, "", String.valueOf(userId),
					String.valueOf(fl.getUid()), String.valueOf(fl
							.getItem_type()),0,"");
		}

		followListService.follow(fl);
        int count = followListService.countAllMyFollowers(fl.getUid(),
                fl.getItem_type());
		ret.setCount(count);

		String contextPath = request.getContextPath();
		ret.setUrl(contextPath + "/fl/unfollow");

		return ret.toString();
	}

	@RequestMapping(value = "/thumbsup", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String thumbsup(HttpServletRequest request, ModelMap model) {
		Object flarray = findFLFromRequestParam(request, true);
		FollowListPO fl = null;
		RetJson ret = null;

		if (flarray instanceof RetJson) {
			ret = (RetJson) flarray;
			//if(ret.code==-2){ return ret.toString(); }
			fl = new FollowListPO();
			
			long userId = Long.parseLong(ret.getFollowerId());			
			
            fl.setFollower_id(userId);             
			fl.setUid(Long.parseLong(ret.getUid()));
			fl.setItem_type(Integer.parseInt(ret.getItemType()));
			if(ret.code == THUMBSUP_ANONYMOUS_CODE){
	            fl.setStatus(FollowStatusType.ANONYMOUS.getIntValue());// initial to special mark for anonymous thumbsup		            
			}else{
	            fl.setStatus(FollowStatusType.UNFOLLOWED.getIntValue());// initial to unfollowed
			}
		} else {
			fl = (FollowListPO) flarray;			
			
			long followerId = ((FollowListPO) fl).getFollower_id();
			
			ret = new RetJson(-1, "", 
			        String.valueOf(followerId),
					String.valueOf(fl.getUid()), 
					String.valueOf(fl.getItem_type()),fl.getThumbsup()?THUMBSUP_ANONYMOUS_ALREADY_CODE : 0,"");
		}
        
        followListService.thumbsup(fl);
		int count = followListService.countAllMyThumbsupers(fl.getUid(),
				fl.getItem_type());
		ret.setCount(count);
        
		String contextPath = request.getContextPath();
        ret.setUrl((contextPath + "/fl/thumbsup/cancel"));
        
        UserProfile up = UserContextHolder.getUserProfile();
        if(up == null){
           ret.setFollowerId("1");//restore to default
        }
        
		return ret.toString();
	}
	
    @RequestMapping(value = "/thumbsup/cancel", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String thumbsupCancel(HttpServletRequest request, ModelMap model) {
        Object flarray = findFLFromRequestParam(request, true);
        FollowListPO fl = null;
        RetJson ret = null;

        if (flarray instanceof RetJson) {
            ret = (RetJson) flarray;
            return ret.toString();
        } else {
            fl = (FollowListPO) flarray;

            long followerId = ((FollowListPO) fl).getFollower_id();
            
            ret = new RetJson(-1, "", 
                    String.valueOf(followerId),
                    String.valueOf(fl.getUid()), 
                    String.valueOf(fl.getItem_type()),0,"");
        }

        followListService.thumbsupCancel(fl);
        int count = followListService.countAllMyThumbsupers(fl.getUid(),
                fl.getItem_type());
        ret.setCount(count);
        
        String contextPath = request.getContextPath();
        ret.setUrl((contextPath + "/fl/thumbsup"));
        
        UserProfile up = UserContextHolder.getUserProfile();
        if(up == null){
           ret.setFollowerId("1");//restore to default
        }
        
        return ret.toString();
    }

	@RequestMapping(value = "/unfollow", method = RequestMethod.POST)
	@ResponseBody
	@Transactional
	public String unfollow(HttpServletRequest request, ModelMap model) {
		Object fl = findFLFromRequestParam(request, false);
		int count = -1;

		assert (fl instanceof FollowListPO);
		if (fl instanceof FollowListPO) {
			followListService.unfollow((FollowListPO) fl);

            count = followListService.countAllMyFollowers(
                    ((FollowListPO) fl).getUid(),
                    ((FollowListPO) fl).getItem_type());

			long userId = ((FollowListPO) fl).getFollower_id();

			String contextPath = request.getContextPath();
			RetJson retJson = new RetJson(count, (contextPath + "/fl/follow"),
					String.valueOf(userId),
					String.valueOf(((FollowListPO) fl).getUid()),
					String.valueOf(((FollowListPO) fl).getItem_type()),0,"");

			return retJson.toString();
		} else {
			return fl.toString();
		}
	}

	private Object findFLFromRequestParam(HttpServletRequest request, boolean forThumbsup) {
		String followerIdStr = request.getParameter("followerId");// follower id
		String uidStr = request.getParameter("uid");// target item which is followed
		String itemTypeStr = request.getParameter("itemType");//0为user, 1为商品, 2为评测, 3为资讯文章,4为直播消息

		long followerId = Long.parseLong(followerIdStr);

		long uid = Long.parseLong(uidStr);
		int itemType = Integer.parseInt(itemTypeStr);
		UserProfile up = UserContextHolder.getUserProfile();
		FollowListPO fl = null;
		long finger = followerId;
		if (up == null) {
		    if(forThumbsup){
		       finger = MobileDetect.getFingerPrint(request);		       
		       fl = followListService.findFollow(uid, finger, itemType);		       
		    }else{
	           return new RetJson(0, "", followerIdStr, uidStr, itemTypeStr,-2,"请登录");		        
		    }		    
		} else {
			followerId = up.getId();
			fl = followListService.findFollow(uid, followerId, itemType);
		}
		if (fl == null) {
		    // create new follow relationship
		    if(forThumbsup){
	           return new RetJson(0, "", String.valueOf(finger), uidStr, itemTypeStr,THUMBSUP_ANONYMOUS_CODE,"");		        
		    }else{
	           return new RetJson(0, "", String.valueOf(followerId), uidStr, itemTypeStr,0,"");		        
		    }
		} else {
		    // existing follow relationship
			return fl;
		}
	}

	public class RetJson {
		int code;
		String message;
		int count;
		String url;
		String followerId;
		String uid;
		String itemType;

		public RetJson() {

		}

		public RetJson(int count, String url, String followerId, String uid,
				String itemType,int code, String message) {
			super();
			this.count = count;
			this.url = url;
			this.followerId = followerId;
			this.uid = uid;
			this.itemType = itemType;
			this.code=code;
			this.message=message;
		}

		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public String getUrl() {
			return url;
		}

		public void setUrl(String url) {
			this.url = url;
		}

		public String getUid() {
			return uid;
		}

		public void setUid(String uid) {
			this.uid = uid;
		}

		public String getFollowerId() {
			return followerId;
		}

		public void setFollowerId(String followerId) {
			this.followerId = followerId;
		}

		public String getItemType() {
			return itemType;
		}

		public void setItemType(String itemType) {
			this.itemType = itemType;
		}

		@Override
		public String toString() {
			return "{ \"count\":\"" + count + "\",\"url\":\"" + url
					+ "\",\"followerId\":\"" + followerId + "\",\"uid\":\""
					+ uid + "\",\"itemType\":\"" + itemType + "\",\"code\":"
					+ code + ",\"message\":\"" + message + "\" }";
		}

	}

}
